<template>
    <!--订单管理-放款申请页面-->
    <div class="applyList contractApplyMng">
    <rui-page :defines="defines" :has-card-box="false" class="contractApply">
        <!-- 查询条件 -->
        <rui-query :label-width="100"
                   isApplyQuery
                   ref="contractMngLoanForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
                   :more-rows="searchMoreOptions">
        </rui-query>
        <!--根据状态查询订单信息 -->
        <div class="table-card">
          <div class="btn-status flex flex-between">
            <div class="loanApplyBtn">
                <template v-for="(item,index) in contractApply">
                    <Button :key="index" :class="activeBtn === item.key ? 'activeBtn btn' :'btn'" size="default"
                            @click="applyStatusQuery(item.key)">{{ item.title }}
                    </Button>
                </template>
            </div>
            <!--            <span v-if="count" style="color: #FF0010;">-->
            <!--                可用加急次数：{{ count }}-->
            <!--          </span>-->
        </div>

        <!--放款申请详情显示页面-->
        <rui-table
            :defineId="'contractMngLoanApplication'"
            :fixed-right="['action']"
            :showIndex="false"
            :select="false"
            :columns="detailsColumns"
            :slots="[{key:'action',slot:'action'},{key:'applyNo',slot:'applyNo'},{key:'contractApplyStatus',slot: 'contractApplyStatus'}]"
            @loadDatas="queryData"
            ref-query="contractMngLoanForm"
            ref="contractMngLoanTable"
            :border="false"
            :fixedLeft="['applyNo']"
        >
            <template slot-scope="{ row, index }" slot="applyNo">
                <a style="color:#3086eb;cursor: pointer;" @click="skipDetail(row)">
                    {{row.applyNo}}
                </a>
            </template>
            <template slot-scope="{ row, index,dataDic }" slot="contractApplyStatus">
                <Badge v-if="row.contractApplyStatus==='01'" text="待提交" color="#e6a23c"/>
                <Badge v-if="row.contractApplyStatus==='02'" text="已提交" color="#999"/>
                <Badge v-if="row.contractApplyStatus==='03'" text="审核中" color="#999"/>
                <Badge v-if="row.contractApplyStatus==='04'" text="审核通过" color="#67c23a"/>
                <Badge v-if="row.contractApplyStatus==='05'" text="已退回" color="#f56c6c"/>
                <Badge v-if="row.contractApplyStatus==='06'" text="合同取消" color="#999"/>
            </template>
            <template slot="action" slot-scope="{ row }">
                <Dropdown style="text-align: center" :transfer="true" class="btn-no-border" transfer-class-name="btn-no-border dropdown-hover-bg">
                    <Button ghost type="primary"  v-if="row.contractApplyStatus==='06' || (row.contractApplyStatus==='04'&& typeof row.startDate!=='undefined')"  disabled>
                        更多
                    </Button>
                    <Button ghost type="primary" v-if="row.contractApplyStatus==='01'||row.contractApplyStatus==='02'||row.contractApplyStatus==='03'||row.contractApplyStatus==='05'||(row.contractApplyStatus==='04'&& typeof row.startDate==='undefined')" >
                        更多
                    </Button>
                    <DropdownMenu slot="list">
                        <DropdownItem  v-if="$store.getters.permissions['apply_loan_withdraw']&&row.contractApplyStatus==='02'&&username!=='admin'"  @click.native="back(row)" size="small">撤回</DropdownItem>
                        <DropdownItem  v-if="$store.getters.permissions['apply_loan_transfer_order']&&(row.contractApplyStatus==='05' || row.contractApplyStatus==='01') && username!=='admin'&& row.createBy===username" @click.native="transfers(row)" size="small">转单</DropdownItem>
                        <DropdownItem  v-if="$store.getters.permissions['apply_loan_cancel']&& typeof row.startDate==='undefined'&&username!=='admin'&& row.contractApplyStatus!=='06'" @click.native="cancelOrder(row)" size="small">取消</DropdownItem>
                        <!--                        <DropdownItem v-if="(row.contractApplyStatus==='03' || row.contractApplyStatus==='01' || row.contractApplyStatus==='02')&&username!=='admin'" @click.native="jumpToSpTap(row)" size="small">特殊业务</DropdownItem>-->
                        <DropdownItem  v-if="$store.getters.permissions['apply_loan_edit']&&(row.contractApplyStatus=='01'||row.contractApplyStatus=='05')&&username!=='admin'" @click.native="edit(row)" size="small">编辑</DropdownItem>
                        <DropdownItem  v-if="$store.getters.permissions['apply_loan_second_order']&&row.gpsStatus=='unPassAudit'&&username!=='admin'" @click.native="distributeTwo(row)" size="small">二次派单</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
            </template>
<!--            <template slot="action" slot-scope="{ row }">-->
<!--                <div class="flex flex-center">-->
<!--                    <Tooltip content="撤回" v-has="'apply_loan_withdraw'" v-show="row.contractApplyStatus==='02'&&username!=='admin'" placement="top" transfer >-->
<!--                        <Icon color="#EB9620" size="20" type="ios-undo-outline" @click.native="back(row)"/>-->
<!--                    </Tooltip>-->
<!--                    <Tooltip content="转单" v-has="'apply_loan_transfer_order'" placement="top" transfer v-show="(row.contractApplyStatus==='05' || row.contractApplyStatus==='01')&& username!=='admin'">-->
<!--                        <Icon color="#EB9620" size="20" type="ios-shuffle" @click.native="transfers(row)"  />-->
<!--                    </Tooltip>-->
<!--                    <Tooltip content="取消" v-has="'apply_loan_cancel'" placement="top" transfer v-show="typeof row.startDate==='undefined'&&username!=='admin'&& row.contractApplyStatus!=='06'">-->
<!--                        <Icon color="#EB9620" size="20" type="ios-close-circle-outline" @click.native="cancelOrder(row)"  />-->
<!--                    </Tooltip>-->
<!--                    <Tooltip content="编辑" v-has="'apply_loan_edit'" placement="top" transfer v-show="(row.contractApplyStatus=='01'||row.contractApplyStatus=='05')&&username!=='admin'" >-->
<!--                        <Icon color="#EB9620" size="20" type="ios-create-outline" @click.native="edit(row)"/>-->
<!--                    </Tooltip>-->
<!--                    <Tooltip content="二次派单" v-has="'apply_loan_second_order'" placement="top" transfer v-show="row.gpsStatus=='unPassAudit'&&username!=='admin'">-->
<!--                        <Icon color="#EB9620" size="20" type="ios-refresh-circle-outline" @click.native="distributeTwo(row)" />-->
<!--                    </Tooltip>-->
<!--                </div>-->
<!--            </template>-->
        </rui-table>
            </div>
        <!--撤回-->
        <Modal v-model="backModalVisible"
               title="撤回页面"
               :width="1100"
               :mask-closable="false" @on-ok="backSubmit">
            <rui-form :form-options="backFormOptions"
                      :read-only="false"
                      ref="backForm">
            </rui-form>
        </Modal>
        <!--转单-->
        <Modal v-model="transferModalVisible"
               title="转单页面"
               :width="1100"
               :mask-closable="false">
            <rui-query :label-width="120"
                       ref="transferForm"
                       :query="transferData"
                       :query-rows="transferFormOptions">
            </rui-query>
            <Button @click.native="refreshUserData" icon="ios-refresh">刷新</Button>
            <rui-table :defineId="'contractMngLoanApplication'"
                       :showIndex="false"
                       :slots="[{key:'action',slot:'action'}]"
                       :columns="transferColumns"
                       @loadDatas="transferData"
                       ref-query="transferForm"
                       ref="transferTable">
                <template slot="action" slot-scope="{ row }">
                    <Button type="primary" @click.native="transferSubmit(row)">转单</Button>
                </template>
            </rui-table>
            <div slot="footer">
                <Button type="primary" @click.native="transferModalVisible=false">返回</Button>
            </div>
        </Modal>
    </rui-page>
    </div>
</template>

<script>
    import contractMngLoanApplication from "../../api/order-mng/contractLoanApplication";
    import {
        getLoanOrderInfo,
        saveBack,
        saveCancel,
        getSpecialInfo,
        searchOprInfoForAssertChange
    } from "../../api/order-mng/contractLoanApplicationApi.js"
    import {getUserInfo} from "../../../basic/api/admin/user";
    import {deepClone} from "../../../../libs/utils/ObjectClone";
    import {getTransferUser} from "../../api/order-mng/loanApplyMngApi";
    import {transferData} from "../../api/order-mng/contractLoanApplicationApi";

    export default {
        computed: {
            defines() {
                return [{id: "contractMngLoanApplication", fields: contractMngLoanApplication}];
            }
        },
        mounted() {
            let obj = this.afs.getPageParams(this);
            if (obj) {
                if (obj.flag == "home") {
                    if (obj.contractApplyStatus) {
                        this.applyStatusQuery(obj.contractApplyStatus);
                    }
                    if(obj.gpsStatus){
                       this.gpsStatusQuery(obj.gpsStatus);
                    }
                } else {
                    this.refresh();
                }
            } else {
                this.refresh();
            }
            this.initGteUserInfo();
        },
        data() {

            return {
                name: "contractMngLoanApplication",
                backModalVisible: false,
                transferModalVisible: false,
                businessType: '',
                disable: false,
                deptId: '',//部门id
                transferDatas: {},//查询转单人员条件
                roleCode: [],//
                roleCodes:'',
                username: '',
                userRealName: '',
                pageData: {
                    pageNumber: 1,
                    pageSize: 10,
                    total: 0
                },
                queryChange: {
                    pageNumber: 1,
                    pageSize: 10,
                    condition: {
                        applyNo: '',
                    }
                },
                queryDate: {},
                count: 5,
                activeBtn: null, //订单状态按钮
                contractApply:[
                    {key:null,title:'全部'},
                    {key:'01',title:'待提交'},
                    {key:'02',title:'已提交'},
                    {key:'03',title:'审核中'},
                    {key:'04',title:'审核通过'},
                    {key:'05',title:'已退回'},
                    {key:'06',title:'合同取消'},
                ],
                //订单管理-放款申请-多条件查询options
                searchStatus: {
                    pageNumber: 1,
                    pageSize: 10,
                    condition: {
                        contractApplyStatus: ""
                    }
                },
                searchFormOptions: [
                    {
                        //isGroup: false,
                        defineId: "contractMngLoanApplication",
                        // fields: ["applyNo", "custName", "businessType"],
                        fields: ["key"],
                    }
                ],
                searchMoreOptions: [

                    {
                        defineId: "contractMngLoanApplication",
                        fields: ["applyNo", "custName", "businessType","applyDateStart", "applyDateEnd", "operateWay", "carType", "carNature", "affiliatedWay","gpsStatus"],
                    }
                ],

                //列表详情显示字段
                detailsColumns: ["custName", "applyNo", "businessType", "carType", "carNature", "loanTerm", "loanAmt", "carVin", "riskPassDate", "lendingFirstDate", "startDate", "gpsStatus", "contractApplyStatus", "realName", "action"],
                //撤回
                backFormOptions: [
                    {
                        isGroup: false,
                        groupName: '撤回页面',
                        grids: [
                            {defineId: "contractMngLoanApplication", fields: ["backReason"]}
                        ]
                    }
                ],
                //转单查询
                transferFormOptions: [
                    {
                        defineId: "contractMngLoanApplication",
                        fields: ["userRealName","phone"]
                    }
                ],
                //转单
                transferColumns: [
                    'userRealName', 'username', 'phone', 'action'
                ],
            };
        },
        watch: {
            '$route'(to, from) {
                if (from.path.indexOf("contract-edit") > -1 || from.path.indexOf("contract-gpsAgainDistribute") > -1) {
                    this.refresh();
                }
            }
        },
        //方法
        methods: {
            //放款-订单管理，跳转合同录入界面
            skipDetail(row) {
                let contractType = true;
                if (typeof row.startDate === "undefined") {
                    contractType = true;

                } else {
                    let thisTime = row.startDate.replace(/-/g, '/');
                    let Time = new Date(thisTime);

                    let time = ((new Date()).getTime() - Time.getTime()) / 1000 / 3600 / 24;
                    if (time >= 15) {
                        contractType = false;
                    }
                }
                let param = {
                    applyNo: row.applyNo,
                    contractNo: row.contractNo,
                    diffType: "details",
                    type: 1,
                    contractType: contractType
                };
                this.afs.newTab(this, 'projects/afs-apply/pages/apply-contract/contract/entry/contract-entry', '放款申请', 'ios-add',
                    param, 'contract-entry' + param.applyNo, [], true);
            },
            //二次派单
            distributeTwo(row) {
                let param = {
                    applyNo: row.applyNo,
                };
                this.afs.newTab(this, 'projects/afs-apply/pages/apply-contract/contract/gps/gpsAgainDistribute', 'GPS二次派单', 'ios-add',
                    param, 'contract-gpsAgainDistribute' + param.applyNo, [], true);
            },
            //根据多条件分页查询放款申请订单信息
            queryData(queryData) {
                this.queryDate = queryData;
                queryData.condition.contractApplyStatus = this.searchStatus.condition.contractApplyStatus;
                getLoanOrderInfo(queryData).then(res => {
                    if (res.code === "0000") {
                        if(typeof res.data!=="undefined") {
                            let {records, total} = res.data;
                            this.$refs.contractMngLoanTable.updateTableData(records, total);
                        }else{
                            this.$refs.contractMngLoanTable.updateTableData([], 0);
                        }
                    }
                });
            },

            edit(row) {
                this.queryChange.condition.applyNo = row.applyNo;
                searchOprInfoForAssertChange(this.queryChange).then(res => {
                    let flag = true;
                    if (res.code === "0000") {
                        if (res.data.length > 0) {
                            for (let i = 0; i < res.data.length; i++) {
                                if (res.data[i].applyType === "ASSERTCHANGE" && res.data[i].applyStatus !== "05" && res.data[i].applyStatus !== "06") {
                                    this.$Message.error("该订单正在申请资产变更，不可操作！");
                                    flag = false;
                                    return;
                                }
                            }
                            if (flag) {
                                let contractType = true;
                                if (typeof row.startDate === "undefined") {
                                    contractType = true;

                                } else {
                                    let thisTime = row.startDate.replace(/-/g, '/');
                                    let Time = new Date(thisTime);

                                    let time = ((new Date()).getTime() - Time.getTime()) / 1000 / 3600 / 24;
                                    if (time >= 15) {
                                        contractType = false;
                                    }
                                }
                                let turn = "contract-edit" + row.applyNo;
                                let param = {
                                    applyNo: row.applyNo,
                                    type: 0,
                                    contractType: contractType,
                                    contractNo: row.contractNo,
                                    contractStatus: row.contractApplyStatus
                                }
                                this.afs.newTab(this, 'projects/afs-apply/pages/apply-contract/contract/entry/contract-entry', '放款申请', 'ios-add',
                                    param,
                                    turn, [], true)
                            }
                        } else {
                            let contractType = true;
                            if (typeof row.startDate === "undefined") {
                                contractType = true;

                            } else {
                                let thisTime = row.startDate.replace(/-/g, '/');
                                let Time = new Date(thisTime);

                                let time = ((new Date()).getTime() - Time.getTime()) / 1000 / 3600 / 24;
                                if (time >= 15) {
                                    contractType = false;
                                }
                            }
                            let turn = "contract-edit" + row.applyNo;
                            let param = {
                                applyNo: row.applyNo,
                                type: 0,
                                contractType: contractType,
                                contractNo: row.contractNo,
                                contractStatus: row.contractApplyStatus
                            }
                            this.afs.newTab(this, 'projects/afs-apply/pages/apply-contract/contract/entry/contract-entry', '放款申请', 'ios-add',
                                param,
                                turn, [], true)
                        }
                    }
                });
            },
            //跳转特殊业务页面
            jumpToSpTap(row) {
                let param = {
                    applyNo: row.applyNo,
                };
                getSpecialInfo(param).then(res => {
                    if (res.code === "0000") {
                        if (res.data != null) {
                            this.$Message.error("此订单已申请特殊业务办理，不可重复办理");
                        } else {
                            this.afs.newTab(this, 'projects/afs-apply/pages/apply-contract/contract/special/specialBusiness', '特殊业务申请', 'ios-add', param, 'specialBusiness' + row.applyNo, [], true)

                        }
                    }
                })
            },
            //根据申请状态查询订单信息
            applyStatusQuery(v) {
                this.activeBtn = v;
                this.searchStatus.condition.contractApplyStatus = v;
                this.searchStatus.pageSize = this.pageData.pageSize;
                this.searchStatus.pageNumber = this.pageData.pageNumber;
                getLoanOrderInfo(this.searchStatus).then(res => {
                    if (res.code === "0000") {
                        if(typeof res.data!=="undefined"){
                            let {records, total} = res.data;
                            this.$refs.contractMngLoanTable.updateTableData(records, total);
                        }else{
                            this.$refs.contractMngLoanTable.updateTableData([], 0);
                        }
                    }
                });
            },
            //根据申请状态查询订单信息
            gpsStatusQuery(v) {
                this.activeBtn = v;
                this.searchStatus.condition.gpsStatus = v;
                this.searchStatus.pageSize = this.pageData.pageSize;
                this.searchStatus.pageNumber = this.pageData.pageNumber;
                getLoanOrderInfo(this.searchStatus).then(res => {
                    if (res.code === "0000") {
                        if(typeof res.data!=="undefined") {
                            let {records, total} = res.data;
                            this.$refs.contractMngLoanTable.updateTableData(records, total);
                        }else{
                            this.$refs.contractMngLoanTable.updateTableData([], 0);
                        }
                    }
                });
            },
            //如果加急次数用完，置灰按钮
            urgentCount() {
                this.count--;
                if (this.count === 0) {
                    console.log(this.count)
                    this.disable = true;
                }
            },
            //初始化获得用户信息
            initGteUserInfo() {
                var role = new Set();
                var roleCodeArr = new Set(['ROLE_PAYMENT', 'ROLE_XCPAYMENT']);
                getUserInfo().then(res => {
                    if (res.code === '0000') {
                        let userExtInfo = res.data.userExtInfo;
                        let roles = deepClone(userExtInfo.roles)
                        roles.forEach(res => {
                            //if roleCode has a same code with roleCodeArr
                            if (roleCodeArr.has(res.roleCode)) {
                                let roleTypeTemp = res.roleTypeTemp;
                                roleTypeTemp[0] ? role.add(roleTypeTemp[0]) : ''
                                roleTypeTemp[1] ? role.add(roleTypeTemp[1]) : ''
                            }
                        });
                        //oldCar for oldCar
                        //newCar for newCar
                        role.has("newCar") ? (this.roleCode.push('ROLE_XCPAYMENT')) : '';
                        role.has("oldCar") ? (this.roleCode.push('ROLE_PAYMENT')) : ''
                        let sysUser = res.data.sysUser;
                        this.deptId = deepClone(sysUser.deptId);
                        this.username = sysUser.username;
                    }
                })
            },
            //刷新
            refreshUserData() {
                this.$refs['transferTable'].reloadData();
            },
            //转单查询人员信息
            transferData(transferData) {
                this.userRealName = transferData.condition.userRealName;
                if (this.businessType === "01") {
                    this.businessType = "newCar";
                    if(this.roleCode.length>0){
                        for(let i=0;i<this.roleCode.length;i++){
                            if(this.roleCode[i]==="ROLE_XCPAYMENT"){
                                this.roleCodes="ROLE_XCPAYMENT";
                            }
                        }
                    }
                } else if (this.businessType === "02") {
                    this.businessType = "oldCar";
                    if(this.roleCode.length>0){
                        for(let i=0;i<this.roleCode.length;i++){
                            if(this.roleCode[i]==="ROLE_PAYMENT"){
                                this.roleCodes="ROLE_PAYMENT";
                            }
                        }
                    }
                }
                this.transferDatas = {
                    roleCode: this.roleCodes,
                    deptId: this.deptId,
                    phone:transferData.condition.phone,
                    username: this.username,
                    userRealName: this.userRealName,
                    businessType: this.businessType
                };
                transferData = this.transferDatas;
                getTransferUser(transferData).then(res => {
                    if (res.code === '0000') {
                        let records = res.data;
                        let total = res.data.length;
                        this.$refs.transferTable.updateTableData(records, total);
                    }
                })
            },
            //刷新
            refresh() {
                // this.searchStatus.condition.contractApplyStatus="";
                this.queryDate = {};
                this.$refs['contractMngLoanTable'].reloadData();
            },
            //转单
            transfers(row) {
                this.transferModalVisible = true;
                this.applyNo = row.applyNo;
                this.businessType = row.businessType;
                this.refreshUserData();
            },
            //保存转单信息,需要转单用户，申请编号
            transferSubmit(row) {
                let params = {
                    createBy: row.username,
                    applyNo: this.applyNo,
                }
                console.log("转单:", row);
                console.log("转单params:", params);
                transferData(params).then(res => {
                    if (res.code === '0000') {
                        this.$Message.success("转单成功")
                    }
                });
            },
            //撤回订单
            back(row) {
                this.$Modal.confirm({
                    title: "确认撤回?",
                    onOk: () => {
                        this.queryChange.condition.applyNo = row.applyNo;
                        searchOprInfoForAssertChange(this.queryChange).then(res => {
                            let flag = true;
                            if (res.code === "0000") {
                                if (res.data.length > 0) {
                                    for (let i = 0; i < res.data.length; i++) {
                                        if (res.data[i].applyType === "ASSERTCHANGE" && res.data[i].applyStatus !== "05" && res.data[i].applyStatus !== "06") {
                                            this.$Message.error("该订单正在申请资产变更，不可操作！");
                                            flag = false;
                                            return;
                                        }
                                    }
                                    if (flag) {
                                        let param = {
                                            contractNo: row.contractNo,
                                            contractApplyStatus: row.contractApplyStatus,
                                            cancelOrWithdraw: 'back'
                                        }
                                        saveCancel(param).then(res => {
                                            if (res.code === "0000") {
                                                this.$Message.success("通知成功");
                                                this.refresh();
                                            }
                                        });
                                    }
                                } else {
                                    let param = {
                                        contractNo: row.contractNo,
                                        contractApplyStatus: row.contractApplyStatus,
                                        cancelOrWithdraw: 'back'
                                    }
                                    saveCancel(param).then(res => {
                                        if (res.code === "0000") {
                                            this.$Message.success("通知成功");
                                            this.refresh();
                                        }
                                    });
                                }
                            }
                        });
                    }
                });
            },
            //保存撤回信息
            backSubmit() {
                this.$refs.backForm.getForm().validate((valid) => {
                    if (valid) {
                        saveBack(this.$refs.backForm.getFormData()).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("撤回成功");
                                this.refresh();
                                this.backModalVisible = false;
                            }
                        }).catch(() => {
                            this.refresh();
                        });
                    }
                });
            },

            //弹出转单
            transfer(row) {
                this.transferModalVisible = true;
            },
            //转单请求提交
            submit() {

            },
            //取消订单
            cancelOrder(row) {
                this.$Modal.confirm({
                    title: "确认取消?",
                    onOk: () => {
                        this.queryChange.condition.applyNo = row.applyNo;
                        searchOprInfoForAssertChange(this.queryChange).then(res => {
                            let flag = true;
                            if (res.code === "0000") {
                                if (res.data.length > 0) {
                                    for (let i = 0; i < res.data.length; i++) {
                                        if (res.data[i].applyType === "ASSERTCHANGE" && res.data[i].applyStatus !== "05" && res.data[i].applyStatus !== "06") {
                                            this.$Message.error("该订单正在申请资产变更，不可操作！");
                                            flag = false;
                                            return;
                                        }
                                    }
                                    if (flag) {
                                        let param = {
                                            contractNo: row.contractNo,
                                            contractApplyStatus: row.contractApplyStatus,
                                            cancelOrWithdraw: 'cancel'
                                        }
                                        saveCancel(param).then(res => {
                                            if (res.code === "0000") {
                                                this.$Message.success("取消成功");
                                                this.refresh();
                                            }
                                        });
                                    }
                                } else {
                                    let param = {
                                        contractNo: row.contractNo,
                                        contractApplyStatus: row.contractApplyStatus,
                                        cancelOrWithdraw: 'cancel'
                                    }
                                    saveCancel(param).then(res => {
                                        if (res.code === "0000") {
                                            this.$Message.success("取消成功");
                                            this.refresh();
                                        }
                                    });
                                }
                            }
                        });
                    }
                });
            }
        }
    }
</script>
<style lang="less" scoped>
@import "../../assets/css/applyList.less";
</style>
